<?php
class MessagesController extends AppController {

	var $name = 'Messages';
		
    var $paginate = array(
        'Message' => array(
	        'limit' => 10,
	        'order' => array(
	            'Message.added' => 'desc',
    			'Message.user_id' => 'asc'
	        ))
    );
    
	var $permissions = array(
		'add' => array('admin','manag','firms','emplo','copyr','users'),
		'index' => array('admin','manag','firms','emplo','copyr','users'),
		'view' => array('admin','manag','firms','emplo','copyr','users'),
		'edit' => array('admin','manag','firms','emplo','copyr','users'),
		'delete' => array('admin','manag','firms','emplo','copyr','users')
	);    
    
    var $statusy = array( );
    
	function beforeFilter(){
		parent::beforeFilter();
		$this->statusy = array(			
			1=>__("Inbox",true),
			2=>__("Outbox",true),
			3=>__("Archives",true),
			41=>__("Deleted",true),
			42=>__("Deleted",true),
			5=>__("Search",true)
		);
	}
	
	public $presetVars = array(
		array('field' => 'searchtext', 'type' => 'like'),
		array('field' => 'user_id', 'type' => 'value')
	);	
	
	public function find() {
		$this->paginate = null;
		
		$this->Prg->commonProcess();
		$this->paginate['conditions'] = $this->Message->parseCriteria($this->passedArgs);	
		$messages = $this->paginate();
		
		$this->set(compact('messages'));
		$this->set('status', '5');
		$this->set('statusy', $this->statusy);		
		$this->autoRender = false;
		$this->render('index');
	}	
	    
	function index($status = '1') {
		$status = ($status == 4) ? array(41,42,43) : $status;
		$this->Message->recursive = 0;
		$messages = $this->paginate('Message',array('Message.user_id'=>$this->Session->read("Auth.User.id"),'Message.status'=>$status));
		$this->set('messages', $messages);
		$this->set('status', $status);
		$this->set('statusy', $this->statusy);
		
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid message', true));
			$this->redirect(array('action' => 'index'));
		}
		$users = $this->_users();
		$this->set(compact('users'));
		$message = $this->Message->read(null, $id);
		if($message['Message']['status'] == 1 ){
			$message['Message']['status'] = 3; /*przeczyatna*/
			if ($this->Message->save($message)){
				$this->Session->setFlash(__('The message has moved to Archives', true));
			}
		}
		$this->set('message', $message);
	}

	function add($user_id=null) {
		$users = $this->_users();
		$this->set(compact('users'));
				
		if (!empty($this->data)) {
			foreach ($this->data['Message']['user_id'] as $user_id => $value_user_id) {
				if($value_user_id == $user_id ){
					$this->data['Message']['added'] = date('Y-m-d H:i:s');
					$this->data['Message']['user_id'] = $user_id;
					$name = (isset($users[$this->Session->read("Auth.User.id")]['name'])) ? $users[$this->Session->read("Auth.User.id")]['name'] : '';
					$surname = (isset($users[$this->Session->read("Auth.User.id")]['surname'])) ? $users[$this->Session->read("Auth.User.id")]['surname'] : '';
					$this->data['Message']['fromto'] = $name.' '.$surname	;
					$this->data['Message']['fromto_user_id'] = $this->Session->read("Auth.User.id");
					$this->data['Message']['status'] = 1 /*new*/;
					$this->Message->create();
					if ($this->Message->save($this->data)){
						
						$to = $this->Message->User->field('email',array('id'=> $user_id ));
						$from = $this->Message->User->field('email',array('id'=>$this->Session->read("Auth.User.id")));
						$subject = $this->data['Message']['name'];
						$content = $this->data['Message']['content'];
						$this->_send($to, $from, $subject, $content);
						
						$this->data['Message']['added'] = date('Y-m-d H:i:s');
						$this->data['Message']['fromto'] = $name.' '.$surname;
						$this->data['Message']['fromto_user_id'] = $user_id;
						$this->data['Message']['status'] = 2 /*wyslane*/;
						$this->data['Message']['user_id'] = $this->Session->read("Auth.User.id"); //musi byc zdeklarowane po nadaniu fromto
						$this->Message->create();
						if (!$this->Message->save($this->data)){	
							$this->Session->setFlash(__('The message could not be saved to sendet box. Please, try again.', true));
						}
						
	
					} else {
						$this->Session->setFlash(__('The message could not be saved. Please, try again.', true));
					}
				}
			}
			$this->redirect(array('action' => 'index'));
		}
		// dodaj dla wybranego uzytkownika
		if(!is_null($user_id)){
			$this->data['Message']['user_id'][$user_id] = $user_id;
			$this->data['Message']['users'] = $this->Message->User->field('email',array('id'=> $user_id )).';';			
		}
	}
	
	private function _users(){
		$filter = array();
		if($this->Session->read("Auth.User.group") == 'admin') $filter = array('admin','manag','emplo','firms','users','copyr');
		if($this->Session->read("Auth.User.group") == 'manag') $filter = array('admin','manag','emplo','firms','users','copyr');
		if($this->Session->read("Auth.User.group") == 'emplo') $filter = array('admin','manag');
		if($this->Session->read("Auth.User.group") == 'firms') $filter = array('admin','manag');
		if($this->Session->read("Auth.User.group") == 'users') $filter = array('admin','manag');
		if($this->Session->read("Auth.User.group") == 'copyr') $filter = array('admin','manag');
		$users_ = $this->Message->User->find('all',array('conditions'=>array('User.group'=>$filter),'order'=>'User.group'));

		$users = array();

		foreach ($users_ as $key => $u) {
			if(!empty($u['Employee'])){
				$users[$u['User']['id']] = $u['Employee'][0];
			}else if(!empty($u['Customer'])){
				$users[$u['User']['id']] = $u['Customer'][0];
			}
			$users[$u['User']['id']]['group'] = $u['User']['group'];
			$users[$u['User']['id']]['email'] = $u['User']['email'];

		}
		if(!array_key_exists($this->Session->read("Auth.User.id"), $users)){
			// dane zalogowanego
			
			$user = $this->Message->User->read(null,$this->Session->read("Auth.User.id"));
			$type = ($this->Session->read("Auth.User.group") != 'firms' )? "Employee" : "Customer";
			$users[$this->Session->read("Auth.User.id")] = $user[$type]['0'];
			$users[$this->Session->read("Auth.User.id")]['group'] = $user['User']['group'];
			$users[$this->Session->read("Auth.User.id")]['email'] = $user['User']['email'];
			
		}
		return $users;
	} 
	
	private function _send($to,$from,$subject,$content){
//		$this->Email->delivery = 'debug';
		
		
	    $this->Email->to = $to; 
        $this->Email->subject = $subject; 
        $this->Email->replyTo = $from; 
        $this->Email->from = __("Cleaning Services Message",true)."<{$from}>"; 
        $this->Email->template = 'default';
        $this->Email->sendAs = 'both';
        
        $this->set('content',$content);
        
         if ( $this->Email->send() ) { 
            $this->Session->setFlash(__('The message has been send', true)); 
        } else { 
            $this->Session->setFlash(__('The message could not be saved to sendet box. Please, try again.', true)); 
        }
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid message', true));
			$this->redirect(array('action' => 'index'));
		}
		$users = $this->_users();
		$this->set(compact('users'));
		
		if (!empty($this->data)) {
			
		
			foreach ($this->data['Message']['user_id'] as $user_id => $value_user_id) {
				if($value_user_id == $user_id ){
					$this->data['Message']['added'] = date('Y-m-d H:i:s');
					$this->data['Message']['user_id'] = $user_id;
					$this->data['Message']['fromto'] = $users[$this->Session->read("Auth.User.id")]['name'].' '.$users[$this->Session->read("Auth.User.id")]['surname'];
					$this->data['Message']['fromto_user_id'] = $this->Session->read("Auth.User.id");
					$this->data['Message']['status'] = 1 /*new*/;
					$this->Message->create();
					if ($this->Message->save($this->data)){
						
						$to = $this->Message->User->field('email',array('id'=> $user_id ));
						$from = $this->Message->User->field('email',array('id'=>$this->Session->read("Auth.User.id")));
						$subject = $this->data['Message']['name'];
						$content = $this->data['Message']['content'];
						$this->_send($to, $from, $subject, $content);
						
						$this->data['Message']['added'] = date('Y-m-d H:i:s');
						$this->data['Message']['fromto'] = $users[$this->data['Message']['user_id']]['name'].' '.$users[$this->data['Message']['user_id']]['surname'];
						$this->data['Message']['fromto_user_id'] = $user_id;
						$this->data['Message']['status'] = 2 /*wyslane*/;
						$this->data['Message']['user_id'] = $this->Session->read("Auth.User.id"); //musi byc zdeklarowane po nadaniu fromto
						$this->Message->create();
						if (!$this->Message->save($this->data)){	
							$this->Session->setFlash(__('The message could not be saved to sendet box. Please, try again.', true));
						}
						
	
					} else {
						$this->Session->setFlash(__('The message could not be saved. Please, try again.', true));
					}
				}
			}			
		}			
		
		if (empty($this->data)) {
			$this->data = $this->Message->read(null, $id);
			$from_uId = $this->data['Message'][(($this->data['Message']['status']==1 || $this->data['Message']['status']==3 || $this->data['Message']['status']==41 || $this->data['Message']['status']== 43)?'fromto_':'').'user_id'];
			$this->data['Message']['user_id'][$from_uId] = $from_uId;
			$this->data['Message']['users'] = $this->Message->User->field('email',array('id'=> $from_uId )).';';	
		}

	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for message', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->data = $this->Message->read(null, $id);
		$status = $this->data['Message']['status'];
		if($status[0] == '4'){
			if ($this->Message->delete($id)) {
				$this->Session->setFlash(__('Message deleted', true));
				$this->redirect(array('action'=>'index',4));
			}			
		}else{
			// dodajemy 4 przed obecny status i tym samym zmieniamy wiadomosc na usunietą
			$this->data['Message']['status'] = '4'.$status;
			if ($this->Message->save($this->data)) {
				$this->Session->setFlash(__('Message deleted', true));
				$this->redirect(array('action'=>'index',$status));
			}
		}
		$this->Session->setFlash(__('Message was not deleted', true));
		$this->redirect(array('action' => 'index',$status));
	}
}
?>